/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: MarketListFragment.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.market.ui;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.bhex.app.R;
import io.bhex.app.base.BaseFragment;
import io.bhex.app.market.adapter.MarketListMultiAdapter;
import io.bhex.app.market.event.ItemClickStatusListener;
import io.bhex.app.market.presenter.MarketListPresenter;
import io.bhex.app.trade.sort.CoinPairComparator;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.view.ShadowDrawable;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.enums.COIN_TYPE;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.quote.bean.OptionCategoryBean;
import io.bhex.sdk.quote.bean.QuoteTokensBean;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * ================================================
 * 描   述：行情列表
 * ================================================
 */

public class MarketListFragment extends BaseFragment<MarketListPresenter, MarketListPresenter.MarketListUI> implements MarketListPresenter.MarketListUI, BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener, View.OnClickListener, DataChangeNotify, ItemClickStatusListener {
    public static final int TYPE_BB = 0;//币币
    public static final int TYPE_OPTION = 1;// 期权
    public static final int TYPE_FUTURES = 2;// 合约
    public static final int TYPE_LEVER = 3;// 杠杆
    public static final int TYPE_CONTRACT = 4;// 合约
    private static final String TGA = "MarketListFragment";
    private static final int TOUCH_DOWN_NOTIFY = 1; //触摸down
    private static final int TOUCH_UP_OR_CANCEL_NOTIFY = 2; //触摸up 或者cancel
    private int mTradeType=TYPE_BB;
    private SwipeRefreshLayout swipeRefresh;
    private RecyclerView recyclerView;
    private MarketListMultiAdapter adapter;
    private View emptyView;
    private String tabName = "";
    private View headerView;
    private List<CoinPairBean> mData;
    private View sortVolView;
    private View sortPriceView;
    private View sortChangeView;
    private Map<Integer, SortBtn> sortViews = new HashMap<>();
    //默认无排序 正常排序0-5
    private int sortType = -1;
    private QuoteTokensBean.TokenItem tabToken;
    private View sortLayoutView;
    //上次时间
    private long lastTime=0l;
    private TextView sortVolTv;
    private TextView sortPriceTv;
    private TextView sortChangeTv;
    private boolean isTouching =false;
    private boolean isVisible;

    @Override
    public void OnDataChangeNotify(QuoteTokensBean.TokenItem tokenData){
        tabToken = tokenData;
        if (tabToken != null) {
            tabName = tabToken.getTokenName();
        }
        //if(getPresenter() != null)
            getCoinPairListData(tabToken);
    }

    @Override
    protected MarketListPresenter.MarketListUI getUI() {
        return this;
    }

    @Override
    protected MarketListPresenter createPresenter() {
        return new MarketListPresenter();
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_market_list_layout, null, false);
    }


    @Override
    protected void initViews() {
        super.initViews();

        Bundle bundle = getArguments();
        if (bundle != null) {
            mTradeType = bundle.getInt("tradeType");
            tabToken = (QuoteTokensBean.TokenItem) bundle.getSerializable("tabToken");
            if (tabToken != null) {
                tabName = tabToken.getTokenName();
            }
            getPresenter().currentItem = tabToken;
        }

        swipeRefresh = viewFinder.find(R.id.swipeRefresh);
        recyclerView = viewFinder.find(R.id.recyclerView);
        LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
//        headerView = layoutInflater.inflate(R.layout.header_market_list_layout, swipeRefresh, false);
        headerView = viewFinder.find(R.id.sortLayoutView);
        emptyView = layoutInflater.inflate(R.layout.empty_layout, swipeRefresh, false);
        ViewGroup.LayoutParams layoutParams = emptyView.getLayoutParams();
        layoutParams.height = PixelUtils.dp2px(300);
        emptyView.setLayoutParams(layoutParams);
        emptyView.findViewById(R.id.empty_txt).setOnClickListener(this);
        emptyView.findViewById(R.id.empty_img).setOnClickListener(this);

        mData = new ArrayList<>();
        adapter = new MarketListMultiAdapter(getActivity(),mData, false, "",this);
//        adapter.addHeaderView(headerView);
//            adapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        adapter.isFirstOnly(false);
//            adapter.setOnLoadMoreListener(this);
        swipeRefresh.setColorSchemeColors(Color.RED, Color.BLUE, Color.GREEN);
        swipeRefresh.setOnRefreshListener(this);
        swipeRefresh.setEnabled(false);

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adapter);
//        adapter.setHeaderAndEmpty(true);
        adapter.setEmptyView(emptyView);

        sortLayoutView = headerView.findViewById(R.id.sortLayoutView);
        sortVolView = headerView.findViewById(R.id.radio_sort_vol);
        sortPriceView = headerView.findViewById(R.id.radio_sort_price);
        sortChangeView = headerView.findViewById(R.id.radio_sort_change);
        SortBtn sortVolBtn = new SortBtn();
        sortVolBtn.setViewId(R.id.radio_sort_vol);
        sortVolBtn.setCheck(false);
        sortVolBtn.setDesc(true);
        sortVolBtn.setBtnIcon((ImageView) headerView.findViewById(R.id.sort_vol_icon));
        sortVolTv = (TextView) headerView.findViewById(R.id.sort_vol);
        sortVolBtn.setBtnTxV(sortVolTv);
        SortBtn sortPriceBtn = new SortBtn();
        sortPriceBtn.setViewId(R.id.radio_sort_price);
        sortPriceBtn.setCheck(false);
        sortPriceBtn.setDesc(true);
        sortPriceBtn.setBtnIcon((ImageView) headerView.findViewById(R.id.sort_price_icon));
        sortPriceTv = (TextView) headerView.findViewById(R.id.sort_price);
        sortPriceBtn.setBtnTxV(sortPriceTv);

        SortBtn sortChangeBtn = new SortBtn();
        sortChangeBtn.setViewId(R.id.radio_sort_change);
        sortChangeBtn.setCheck(false);
        sortChangeBtn.setDesc(true);
        sortChangeBtn.setBtnIcon((ImageView) headerView.findViewById(R.id.sort_change_icon));
        sortChangeTv = (TextView) headerView.findViewById(R.id.sort_change);
        sortChangeBtn.setBtnTxV(sortChangeTv);

        sortViews.put(R.id.radio_sort_vol, sortVolBtn);
        sortViews.put(R.id.radio_sort_price, sortPriceBtn);
        sortViews.put(R.id.radio_sort_change, sortChangeBtn);
        for (Integer key : sortViews.keySet()) {
            SortBtn sortBtn = sortViews.get(key);
            setShadow(sortBtn);
        }

        if (sortLayoutView != null) {
            sortLayoutView.setVisibility(mTradeType==TYPE_OPTION?View.GONE:View.VISIBLE);//期权隐藏排序
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        for (Integer key : sortViews.keySet()) {
            SortBtn sortBtn = sortViews.get(key);
            setShadow(sortBtn);
        }
        sortVolTv.setTextColor(ContextCompat.getColor(getActivity(), CommonUtil.isBlackMode()? R.color.dark_night : R.color.dark));
        sortPriceTv.setTextColor(ContextCompat.getColor(getActivity(), CommonUtil.isBlackMode()? R.color.dark_night : R.color.dark));
        sortChangeTv.setTextColor(ContextCompat.getColor(getActivity(), CommonUtil.isBlackMode()? R.color.dark_night : R.color.dark));
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case TOUCH_DOWN_NOTIFY:
                    isTouching = false;
                    showMarket(mData);
                    break;
                case TOUCH_UP_OR_CANCEL_NOTIFY:
                    isTouching = false;
                    showMarket(mData);
                    break;
            }
        }
    };

    @Override
    public void onVisibleChanged(boolean visible) {
        super.onVisibleChanged(visible);
        isVisible = visible;
        DebugLog.e("FragmentXX", " MarketListFragment isVisible = " + isVisible +"  "+tabName +"  "+ this.toString());
//        DebugLog.e("MARKET-Update",visible ? "visible   " : "invisible  " + this.hashCode());
        if (visible) {
            getCoinPairListData(tabToken);
        }
    }

    @Override
    public void onItemStatusListener(boolean isClick) {
        if (isClick) {
            isTouching = true;
            mHandler.sendEmptyMessageDelayed(TOUCH_DOWN_NOTIFY,1000);
        }else{
            mHandler.sendEmptyMessageDelayed(TOUCH_UP_OR_CANCEL_NOTIFY,200);
        }
    }

    public void getCoinPairListData(final QuoteTokensBean.TokenItem tokenItem){
//        DebugLog.e("Fragment","MarketListFragment return data = " + tokenItem.getTokenId());

        if (System.currentTimeMillis()-lastTime<200){
            return;
        }
        if(tokenItem == null)
            return;

        Observable.create((ObservableOnSubscribe<List<CoinPairBean>>) emitter -> {

            tabToken = tokenItem;
            HashMap<String, CoinPairBean> coinPairMap = tabToken.getCoinPairMap();
            List<CoinPairBean> coinPairList = new ArrayList<>();

            for (String key : coinPairMap.keySet()) {
                CoinPairBean coinPairBean = coinPairMap.get(key);
                coinPairList.add(coinPairBean);
            }

            /** TODO 期权主板 创新板特殊处理  ***********************/
            //期权分类
            HashMap<String, OptionCategoryBean> optionCategoryMap = SymbolDataManager.GetInstance().getOptionCategoryMap();
            for (String key : optionCategoryMap.keySet()) {
                optionCategoryMap.get(key).getCoinPairList().clear();
            }

            boolean isOption = false;
            if (coinPairList != null&&coinPairList.size()>0) {
                for (int i = 0; i < coinPairList.size(); i++) {
                    CoinPairBean coinPairBean = coinPairList.get(i);
                    if (coinPairBean.baseTokenOption != null) {
                        //判断是期权
                        isOption = true;
                        String firstLevelUnderlyingId = coinPairBean.getFirstLevelUnderlyingId();
                        OptionCategoryBean optionCategory = SymbolDataManager.GetInstance().getOptionCategoryMap(firstLevelUnderlyingId);
                        if (optionCategory != null) {
                            List<CoinPairBean> coinPairList1 = optionCategory.getCoinPairList();
                            if (coinPairList1 != null) {
                                coinPairList1.add(coinPairBean);
                            }
                        }
                    }
                }
            }

            if (isOption) {
                coinPairList.clear();
                for (String key : optionCategoryMap.keySet()) {
                    OptionCategoryBean optionCategoryBean = optionCategoryMap.get(key);
                    if (optionCategoryBean != null) {
                        List<CoinPairBean> coinPairList1 = optionCategoryBean.getCoinPairList();
                        if (coinPairList1 != null&&coinPairList1.size()>0) {
                            //先添加主板信息
                            CoinPairBean coinPairBean1 = new CoinPairBean();
                            coinPairBean1.setCoinType(COIN_TYPE.COIN_TYPE_OPTION.getCoinType());
                            coinPairBean1.setItemShowType(MarketListMultiAdapter.ITEM_TYPE_OPTION_CATEGORY);
                            CoinPairBean.BaseTokenOption baseTokenOption1 = new CoinPairBean.BaseTokenOption();
                            baseTokenOption1.dataCategory = 1;
                            baseTokenOption1.categoryName = optionCategoryBean.getName();
                            coinPairBean1.baseTokenOption=baseTokenOption1;
                            coinPairList.add(coinPairBean1);
                            //再添加主板下对应的币对
                            coinPairList.addAll(coinPairList1);
                        }
                    }
                }

            }

            emitter.onNext(coinPairList);
//                emitter.onComplete();
        }).subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<CoinPairBean>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(List<CoinPairBean> coinPairList) {
                showMarket(coinPairList);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });



    }

    @Override
    protected void addEvent() {
        super.addEvent();
        headerView.findViewById(R.id.radio_sort_vol).setOnClickListener(this);
        headerView.findViewById(R.id.radio_sort_price).setOnClickListener(this);
        headerView.findViewById(R.id.radio_sort_change).setOnClickListener(this);

    }

    @Override
    public void onLoadMoreRequested() {
        swipeRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                adapter.loadMoreComplete();
            }
        }, 500);
    }

    @Override
    public void onRefresh() {
        setRefreshing(false);
    }


    public void setRefreshing(final boolean refreshing) {
        swipeRefresh.post(new Runnable() {
            @Override
            public void run() {
                swipeRefresh.setRefreshing(refreshing);
            }
        });
    }

    /**
     * 展示行情
     *
     * @param coinPairList
     */
    @Override
    public void showMarket(List<CoinPairBean> coinPairList) {
//        if (!isVisible) {
//            return;
//        }

        mData = coinPairList;
        if(adapter == null)
            return;
//        DebugLog.e("MARKET VALIDATE TEST 2 = "+ this.hashCode()+ " : " + isTouching);
        if (!isTouching) {  //如果处于点击操作时，暂时不更新UI
            if (sortType == -1) {
                adapter.setNewData(mData);
            } else {
                sortByComparator(mData, sortType);
            }
        }

    }

    @Override
    public String getTabName() {
        return tabName;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.empty_txt:
            case R.id.empty_img:
                //TODO 例如重试处理
                break;
            case R.id.radio_sort_vol:
                sort(R.id.radio_sort_vol);
                break;
            case R.id.radio_sort_price:
                sort(R.id.radio_sort_price);
                break;
            case R.id.radio_sort_change:
                sort(R.id.radio_sort_change);
                break;
            case R.id.btnAddFavorite:
                IntentUtils.goSearch(getActivity());
                break;

        }
    }

    /**
     * 排序
     *
     * @param viewId
     */
    private void sort(int viewId) {
        changeSortBtnStatus(viewId);
        if (mData != null) {
            SortBtn sortBtn = sortViews.get(viewId);
            switch (viewId) {
                case R.id.radio_sort_vol:
                    sortType = sortBtn.isDesc() ? CoinPairComparator.SORT_TYPE_VOL_DESC : CoinPairComparator.SORT_TYPE_VOL_ASC;
                    break;
                case R.id.radio_sort_price:
                    sortType = sortBtn.isDesc() ? CoinPairComparator.SORT_TYPE_PRICE_DESC : CoinPairComparator.SORT_TYPE_PRICE_ASC;
                    break;
                case R.id.radio_sort_change:
                    sortType = sortBtn.isDesc() ? CoinPairComparator.SORT_TYPE_CHANGE_DESC : CoinPairComparator.SORT_TYPE_CHANGE_ASC;
                    break;
            }

            sortByComparator(mData, sortType);

        }

    }

    /**
     * 比较器排序
     *
     * @param mData
     * @param sortType
     */
    private void sortByComparator(List<CoinPairBean> mData, int sortType) {
        Collections.sort(mData, new CoinPairComparator(sortType));
//        adapter.notifyDataSetChanged();
        adapter.setNewData(mData);
    }

    /**
     * 修改排序按钮的状态
     *
     * @param viewId
     */
    private void changeSortBtnStatus(int viewId) {
        for (Integer key : sortViews.keySet()) {
            SortBtn sortView = sortViews.get(key);
            if (sortView.getViewId() == viewId && sortView.isCheck()) {
                //如果之前为选中排序状态，再次点击则反向排序
                sortView.setDesc(!sortView.isDesc());
            } else {
                //默认是降序状态
                sortView.setDesc(true);
            }
            if (sortView.getViewId() == viewId) {
                sortView.setCheck(true);
            } else {
                sortView.setCheck(false);
            }
            setShadow(sortView);
            changeBtnTxtAndIcon(sortView);
        }

    }


    /**
     * 设置背景和阴影
     *
     * @param sortBtn
     */
    private void setShadow(SortBtn sortBtn) {
        ShadowDrawable.setShadowDrawable(headerView.findViewById(sortBtn.getViewId()),
                sortBtn.isCheck() ? getResources().getColor(R.color.blue) : getResources().getColor(
                        CommonUtil.isBlackMode() ? R.color.white_night : R.color.white),
                PixelUtils.dp2px(3),
                sortBtn.isCheck() ? getResources().getColor(R.color.blue10) : getResources().getColor(
                        CommonUtil.isBlackMode() ? R.color.dark10_night : R.color.dark10),
                PixelUtils.dp2px(3),
                1,
                PixelUtils.dp2px(1));

    }

    /**
     * 改变排序按钮文本颜色和icon
     *
     * @param sortView
     */
    private void changeBtnTxtAndIcon(SortBtn sortView) {
        if (sortView.isCheck()) {
            sortView.getBtnTxV().setTextColor(getResources().getColor(CommonUtil.isBlackMode() ? R.color.dark_night : R.color.white));
            sortView.getBtnIcon().setImageResource(sortView.isDesc() ? R.mipmap.icon_sort_checked_down : R.mipmap.icon_sort_checked_up);
        } else {
            sortView.getBtnTxV().setTextColor(getResources().getColor(CommonUtil.isBlackMode() ? R.color.dark_night : R.color.dark));
            sortView.getBtnIcon().setImageResource(R.mipmap.icon_sort);
        }
    }

    public class SortBtn {
        private int viewId;
        private TextView btnTxV;
        private ImageView btnIcon;
        private boolean check;//是否选中
        private boolean desc;//是否是降序

        public int getViewId() {
            return viewId;
        }

        public void setViewId(int viewId) {
            this.viewId = viewId;
        }

        public boolean isCheck() {
            return check;
        }

        public void setCheck(boolean check) {
            this.check = check;
        }

        public boolean isDesc() {
            return desc;
        }

        public void setDesc(boolean desc) {
            this.desc = desc;
        }

        public TextView getBtnTxV() {
            return btnTxV;
        }

        public void setBtnTxV(TextView btnTxV) {
            this.btnTxV = btnTxV;
        }

        public ImageView getBtnIcon() {
            return btnIcon;
        }

        public void setBtnIcon(ImageView btnIcon) {
            this.btnIcon = btnIcon;
        }
    }

}
